<template>
	<uni-popup ref="popup" type="bottom" @change="popupChange">
		<view class='bg-white'>
			<PickerTitle @cancel="close" @ok="ok" :title="title"/>
			<picker-view style="height: 500rpx;width:750rpx;" :value="pickerValue" @change="pickerChange">
				<picker-view-column>
					<view class='h-10 flex-center text-hide' v-for="(item, index) in data" :key="item.value">
						<text class="text-m color-main">{{ item.text }}</text>
					</view>
				</picker-view-column>
			</picker-view>
		</view>
	</uni-popup>
</template>

<script>
import { ref, watch, nextTick } from 'vue';
import PickerTitle from "./picker-title.vue";
export default {
	components: {
		PickerTitle
	},
	props: {
		data: Array,
		title: String,
	},
	emits: ["pick"],
	setup(props, ctx) {
		const popup = ref();
		//索引
		const pickerValue = ref([0]);
		function popupChange(e) {
		}
		function pickerChange(e) {
			pickerValue.value = e.detail.value;
		}
		function open(options = {}){
			if(options.value){
				//value要转化为索引
				const index = props.data.findIndex((el) => el.value === options.value);
				pickerValue.value = index === -1 ? [0] : [index];
			}
			popup.value.open();
		}
		function close(){
			popup.value.close();
		}
		function ok(){
			let val = pickerValue.value[0];
			let target = null;
			if(val === undefined){
				val = null;
			} else {
				target = props.data[val];
				val = target ? target.value : null;
			}
			ctx.emit("pick", {
				value: val,
				item: target
			});
			close();
		}
		return {
			popupChange,
			pickerChange,
			pickerValue,
			open,
			close,
			ok,
			popup,
		};
	},
};
</script>

<style></style>
